<template>
	<view class="app">
		<authorize @onLoadFun="onLoadFun"></authorize>
		<view class="app-container">
			<view class="confirm-wrap">
				<view class="card" @tap="openDocument">
					<text class="text-default">文件</text>
					<text class="text-gray fr">
						查看
						<text class="cuIcon-right"></text>
					</text>
				</view>
				<view class="card">
					<view class="cu-list menu">
						<view class="item">
							<view class="content"><text>打印内容</text></view>
							<text class="text-gray action">
								{{ selectedSpec.name || '' }}
								<text class="cuIcon-right"></text>
							</text>
						</view>
						<view class="item">
							<view class="content"><text>打印类型</text></view>
							<view class="text-gray action">
								<picker @change="pickerChange" :value="currentIndex" :range="picker" range-key="name">
									<view class="picker">
										<text>{{ picker[currentIndex].name }}</text>
										<text class="cuIcon-right"></text>
									</view>
								</picker>
							</view>
						</view>
						<view class="item">
							<view class="content"><text>打印份数</text></view>
							<view class="text-gray action"><NumberInput v-model.number="num"></NumberInput></view>
						</view>
						<view class="item">
							<view class="content"><text>文档页数</text></view>
							<text class="text-gray action">{{ selectedFilePage }}页</text>
						</view>
					</view>
				</view>
				<view class="card">
					<view class="cu-list menu">
						<view class="item">
							<view class="content"><text>支付方式</text></view>
							<view class="text-gray action">
								<picker @change="pickerPaymentMethodsChange" :value="paymentMethodIndex" :range="paymentMethods" range-key="name">
									<view class="picker">
										<text>{{ paymentMethods[paymentMethodIndex].name }}</text>
										<text class="cuIcon-right"></text>
									</view>
								</picker>
							</view>
						</view>
						<view class="item">
							<view class="content"><text>使用优惠券</text></view>
							<text class="text-gray action" @tap="filterCouponsEvent">
								{{couponsIndex > -1 ? filterCoupons[couponsIndex].discount_coupon_name : '请选择优惠券'}}
								<text class="cuIcon-right"></text>
							</text>
						</view>
						<view class="item">
							<view class="content"><text>合计费用</text></view>
							<text class="text-default price">￥{{ couponsIndex > -1 ? filterCoupons[couponsIndex].type ? totalPrice * couponPrice > 0 ? (totalPrice * couponPrice).toFixed(2) : 0 : totalPrice - couponPrice > 0 ? (totalPrice - couponPrice).toFixed(2) : 0 : totalPrice}}</text>
						</view>
					</view>
				</view>
				<button class="form-btn cu-btn block bg-primary lg" :disabled="comfirmDisable" @tap="redirectToResult">预约</button>
				<!--				<button class="form-btn cu-btn block bg-primary lg" @tap="downloadFile">下载</button>-->
			</view>
		</view>
		<PaymentModal ref="PaymentModal" :title="paymentModalTitle" v-model="payFlag" @confirm="confirmPassword"></PaymentModal>
		<CouponsList v-model="couponsListVisibility" :coupon="filterCoupons" :openType="1" @changCoupons="changCoupons"></CouponsList>
	</view>
</template>

<script>
import NumberInput from './components/number-input/number-input.vue';
import { createCloudPrinterOrder } from '../api/print';
import { VUE_APP_BASE_API } from '../common/tools/config';
import Authorize from '@/components/authorize/authorize';
import PaymentModal from '@/components/payment-modal/password.vue';
import { getUserInfo, changePaymentCode } from '@/api/user';
import { paymentInterface } from '@/api/pay';
import { getWechatUserDiscountCouponInfoList } from '@/api/common.js';
import { CouponsList } from '@/components/coupons-list/coupons-list.vue';
import { sub } from '@/common/tools/util.js'
export default {
	components: {
		NumberInput,
		PaymentModal,
		Authorize,
		CouponsList
	},
	data() {
		return {
			num: 1,
			//支付方式
			paymentMethods: [
				{
					name: '微信支付',
					value: 2
				},
				{
					name: '余额支付',
					value: 1
				}
			],
			//优惠券列表
			coupons: [],
			//过滤不符合条件得优惠券列表
			filterCoupons: [],
			//选择的优惠券下标
			couponsIndex: -1,
			//优惠券组件 dialog 框
			couponsListVisibility: false,
			//选择的支付方式下标
			paymentMethodIndex: 0,
			picker: [
				{
					name: '单面',
					value: 0
				},
				{
					name: '双面',
					value: 1
				}
			],
			userInfo: {},
			currentIndex: 0,
			//控制余额支付显示隐藏
			payFlag: false,
			//余额支付组件标题
			paymentModalTitle: '',
			//生成订单号的返回值
			order_result: {},
			//防误操作
			isDisabled: false,
			
			comfirmDisable: false
		};
	},
	computed: {
		totalPrice() {
			const price = this.picker[this.currentIndex].value === 0 ? this.selectedSpec.one_side_unit_price : this.selectedSpec.two_side_unit_price;
			const page = this.picker[this.currentIndex].value === 0 ? this.selectedFilePage : Math.ceil(this.selectedFilePage / 2);
			const total = Number(price) * this.num * page
			return total > 0 ? total.toFixed(2) : 0;
		},
		couponPrice() {
			const coupon = this.filterCoupons[this.couponsIndex]
			//判断使用使用优惠券
			//判断优惠券类型，0为立减，1为折扣
			return this.couponsIndex > -1 ? coupon.type ? Number(coupon.discount) * 0.1 : Number(coupon.subtract_price) : 0
		},
		selectedSpec() {
			return getApp().globalData.uploadFileInfo['spec'];
		},
		selectedFile() {
			return getApp().globalData.uploadFileInfo['path'];
		},
		selectedFilePage() {
			return getApp().globalData.uploadFileInfo['page_num'];
		}
	},
	watch: {
		num() {
			this.couponsIndex = -1
			this.coupons.forEach( v => {
				v['is_use'] = false
			})
		}
	},
	methods: {
		onLoadFun() {
			if (this.selectedFilePage <= 0) {
				this.comfirmDisable = true
				wx.showToast({
					icon: 'none',
					title: '该文件格式异常，请重新上传文件'
				});
				return setTimeout(() => {
					uni.navigateBack();
				}, 1000);
			} else {
				this.getUserInfoEvent();
				this.getCouponInfoList();
			}
		},
		getUserInfoEvent() {
			return new Promise((resolve, reject) => {
				getUserInfo().then(res => {
					this.userInfo = res.result;
					resolve(res.result);
				});
			});
		},
		/**
		 * 选择打印类型
		 * @param e 单/双面
		 */
		pickerChange(e) {
			const index = e.detail.value
			const item = this.picker[index]
			const selectedSpec = this.selectedSpec
			// selectedSpec判断是否图片 pickerChange判断打印类型
			// 打印图片无法双面
			if (item.value === 1 && selectedSpec.type === 1) {
				uni.showToast({
					icon: 'none',
					title: '打印图片无法双面'
				});
				return;
			}
			this.currentIndex = e.detail.value;
			this.coupons.forEach( v => {
				v['is_use'] = false
			})
			this.couponsIndex = -1
		},
		/**
		 * 查询用户优惠券信息列表
		 */
		getCouponInfoList() {
			getWechatUserDiscountCouponInfoList({
				type: 2
			}).then(res => {
				this.coupons = res.result.showing
			})
		},
		/**
		 * 选择支付方式
		 * @param e 微信/余额
		 */
		pickerPaymentMethodsChange(e) {
			// 微信支付封印
			// if (e.detail.value === '0') {
			// 	uni.showToast({
			// 		icon: 'none',
			// 		title: '微信支付功能正在建设中~(๑•̀ㅂ•́)و✧'
			// 	});
			// 	return;
			// }
			this.paymentMethodIndex = e.detail.value;
		},
		/**
		 * 过滤当前价格可使用的优惠券
		 */
		filterCouponsEvent() {
			this.couponsListVisibility =  true
			this.filterCoupons = this.coupons.filter(v => {
				return Number(this.totalPrice) >= Number(v.full_price)
			})
			console.log(this.filterCoupons)
		},
		/**
		 * 选择优惠券
		 * @param e 优惠券
		 */
		changCoupons(item, index) {
			//把全部可用优惠券变为未使用状态
			this.filterCoupons.forEach( v => {
				v.is_use = false
			})
			//判断选择项是否被使用状态 取反
			if (item.is_use) {
				item.is_use = false
				index = -1
			}else {
				item.is_use = true
			}
			this.coupons.forEach(v => {
				if(v.discount_coupon_id === item.discount_coupon_id) {
					v.is_use = item.is_use
				}
			})
			this.couponsIndex = index
		},
		redirectToResult() {
			if (this.isDisabled) return;
			this.isDisabled = true;

			//没有生成订单号时
			if (!this.order_result.order_number) {
				let that = this;
				//微信支付
				if (this.paymentMethods[this.paymentMethodIndex].value === 2) {
					// 消息订阅
					const tmplIds = [
						'AIg8hKVRSl726FldNGbSCfWEmeKk7-LURrLsAXE32Fs',
						'CfaD2gTrrQFN13wTxlVGfsKIv15VPmPVF46XL1mZPY4',
						'hhpFPLWhR6_oTBTXK6olAfYlzBip3zVGlzNmV97FSkQ'
					]
					uni.requestSubscribeMessage({
						tmplIds: tmplIds,
						success (res) {
							if (
								res['AIg8hKVRSl726FldNGbSCfWEmeKk7-LURrLsAXE32Fs'] !== 'accept' ||
								res['CfaD2gTrrQFN13wTxlVGfsKIv15VPmPVF46XL1mZPY4'] !== 'accept' ||
								res['hhpFPLWhR6_oTBTXK6olAfYlzBip3zVGlzNmV97FSkQ'] !== 'accept'
							) {
								uni.showToast({
									icon: 'none',
									title: '请全选允许消息订阅'
								});
								that.isDisabled = false;
								return;
							} else {
								//第一步：生成订单号
								that.createCloudPrinterOrderEvent().then(order_result => {
									that.payType(order_result);
								});
							}
						}
					});
				} else {
					// 消息订阅
					const tmplIds = [
						'CfaD2gTrrQFN13wTxlVGfsKIv15VPmPVF46XL1mZPY4',
						'hhpFPLWhR6_oTBTXK6olAfYlzBip3zVGlzNmV97FSkQ',
					]
					uni.requestSubscribeMessage({
						tmplIds: tmplIds,
						success (res) {
							if (
								res['CfaD2gTrrQFN13wTxlVGfsKIv15VPmPVF46XL1mZPY4'] !== 'accept' ||
								res['hhpFPLWhR6_oTBTXK6olAfYlzBip3zVGlzNmV97FSkQ'] !== 'accept'
							) {
								uni.showToast({
									icon: 'none',
									title: '请全选允许消息订阅'
								});
								that.isDisabled = false;
								return;
							} else {
								//第一步：生成订单号
								that.createCloudPrinterOrderEvent().then(order_result => {
									that.payType(order_result);
								});
							}
						}
					});
				}
			} else {
				this.payType({
					order_number: this.order_result.order_number
				});
				this.isDisabled = false;
			}
		},
		/**
		 * 判断支付方式 采取不同方法
		 * @param {Object} 订单编号
		 */
		payType(res) {
			//余额支付
			if (this.paymentMethods[this.paymentMethodIndex].value === 1) {
				//验证密码
				this.payFlag = true;
				this.paymentModalTitle = this.userInfo.is_set_payment_code === 0 ? '设置安全密码' : '校验安全密码';
			}
			//微信支付
			else {
				uni.redirectTo({
					url: `/print-pages/result?print_order_id=${res.print_order_id}&type=${this.paymentMethods[this.paymentMethodIndex].value}`
				});
				// if(res.is_actual_price_zero) {
					// uni.redirectTo({
					// 	url: `/print-pages/result?print_order_id=${res.print_order_id}&type=${this.paymentMethods[this.paymentMethodIndex].value}`
					// });
				// }else {
				// 	//第二步：获取支付参数
				// 	this.paymentInterfaceEvent().then(result => {
				// 		//第三步：发起微信支付
				// 		this.payEvent(result, res);
				// 	});
				// }
			}
		},
		/**
		 *  生成订单号
		 */
		createCloudPrinterOrderEvent() {
			return new Promise((resolve, reject) => {
				const selectedSpec = this.selectedSpec;
				createCloudPrinterOrder({
					file_name: getApp().globalData.uploadFileInfo.file_name,
					file_path: this.selectedFile,
					file_page_number: this.selectedFilePage,
					discount_coupon_id: this.couponsIndex > -1 ? this.filterCoupons[this.couponsIndex].discount_coupon_id : '',
					cloud_print_type_id: selectedSpec.cloud_print_type_id,
					is_two_sided_print: this.picker[this.currentIndex].value,
					copies: this.num,
					payment_type: this.paymentMethods[this.paymentMethodIndex].value,
				})
					.then(res => {
						this.order_result = res.result;
						this.isDisabled = false;
						resolve(res.result);
					})
					.catch(err => {
						this.isDisabled = false;
						reject();
					});
			});
		},
		/**
		 *  获取支付流水号
		 */
		paymentInterfaceEvent(password) {
			return new Promise(resolve => {
				const order_result = this.order_result;
				paymentInterface({
					payType: this.paymentMethods[this.paymentMethodIndex].value,
					body: this.selectedSpec.name,
					out_trade_no: order_result.order_number,
					order_id: order_result.print_order_id || '',
					payment_code: password || '',
					orderType: 1
				}).then(res => {
					console.error(res);
					resolve(res.result);
				});
			});
		},
		/**
		 * 支付
		 * @param result
		 * @param item
		 */
		payEvent(result, item) {
			const { nonceStr, paySign, signType, timeStamp } = result;
			wx.requestPayment({
				nonceStr: nonceStr,
				package: result.package,
				paySign: paySign,
				signType: signType,
				timeStamp: timeStamp.toString(),
				success: res => {
					const order_result = this.order_result;
					if (res.errMsg === 'requestPayment:ok') {
						uni.redirectTo({
							url: `/print-pages/result?print_order_id=${order_result.print_order_id}&type=${this.paymentMethods[this.paymentMethodIndex].value}`
						});
					}
				},
				fail: res => {
					if (res.errMsg !== 'requestPayment:fail cancel') {
						wx.showModal({
							title: '支付错误',
							content: '可能遇到网络堵塞，建议重新尝试提交预约'
						});
					}
					wx.redirectTo({
						url: '/user-pages/history'
					});
				}
			});
		},
		/**
		 * 关闭余额支付弹窗
		 */
		hideModal() {
			this.$refs.PaymentModal.hideModal();
		},
		/**
		 * 输入密码后确认事件
		 * @param {Object} value 密码
		 */
		confirmPassword(value) {
			if (this.userInfo.is_set_payment_code === 0) {
				//调接口
				changePaymentCode({
					payment_code: value
				}).then(res=> {
					this.userInfo.is_set_payment_code = 1;
					this.hideModal();
					clearTimeout(this.timer);
					this.timer = setTimeout(() => {
						this.payFlag = true;
						this.paymentModalTitle = this.userInfo.is_set_payment_code === 0 ? '设置安全密码' : '校验安全密码';
					}, 1000);
				}).catch(err => {
					this.$refs.PaymentModal.clear()
				})
			} else {
				const order_result = this.order_result;
				//第二步：获取支付参数
				this.paymentInterfaceEvent(value).then(res => {
					uni.redirectTo({
						url: `/print-pages/result?print_order_id=${order_result.print_order_id}&type=${this.paymentMethods[this.paymentMethodIndex].value}`
					});
				});
				this.hideModal();
			}
		},
		/**
		 * 新开页面打开文档
		 */
		openDocument() {
			const reg = RegExp(VUE_APP_BASE_API)
			const selectedFile = reg.test(this.selectedFile) ? this.selectedFile : VUE_APP_BASE_API + this.selectedFile;
			const selectedSpecType = this.selectedSpec.type;
			uni.showLoading({ title: '加载中', mask: true });
			uni.downloadFile({
				url: selectedFile,
				success: function(res) {
					uni.hideLoading();
					const filePath = res.tempFilePath;
					if (selectedSpecType === 0) {
						uni.openDocument({
							filePath: filePath,
							success: function(res) {
								console.log('打开文档成功');
							}
						});
					} else {
						uni.previewImage({
							current: filePath, // 当前显示图片的http链接
							urls: [filePath] // 需要预览的图片http链接列表
						});
					}
				}
			});
		}
	}
};
</script>

<style lang="scss">
.confirm-wrap {
	float: right;
	width: 80%;

	.card {
		border-radius: $uni-border-radius-base 0 0 $uni-border-radius-base !important;
	}

	.item {
		position: relative;
		display: flex;
		min-height: 35px;
		background-color: #ffffff;
		justify-content: space-between;
		align-items: center;
		color: $uni-text-color;

		.content {
			line-height: 1.6em;
			flex: 1;
		}

		.action {
			color: #aaaaaa;
		}
	}

	.form-btn {
		border-radius: $uni-border-radius-base 0 0 $uni-border-radius-base !important;
		box-shadow: $uni-box-shadow;
	}
}
</style>
